<?php
Globals::requireController('Admin');
Globals::requireTable('User');
Globals::requireTable('Group');

class UserController extends AdminController
{
	protected $userTable;
	protected $groupTable;
	
	public function __construct($config = null)
	{
		parent::__construct($config, 'user');
		
		$this->userTable	= new UserTable($config);
		$this->groupTable	= new GroupTable($config);
	}
	
	public function indexAction()
	{
		$where	= array();
		$id		= $this->getIntParam('id');
		$groupid= $this->getIntParam('groupid');
		
		if ($id)
			$where['id'] = $id;
		
		if ($groupid)
			$where['groupid'] = $groupid;
		
		$this->view->data		= $this->userTable->listAll($where, 'id ASC');
		$this->view->groupTable	= $this->groupTable;
	}
	
	public function addAction()
	{
		$this->view->groupData = $this->groupTable->listAll(null, 'id ASC');
	}
	
	public function addPostAction()
	{
		$id = $this->userTable->add($this->getParams('username,password,groupid,realname'), true);
		$this->log('添加用户'.($id ? '成功(id: '.$id.')' : '失败'));
		$this->redirectToAction();
	}
	
	public function modifyAction()
	{
		$id	= $this->getIntParam('id');
		$row= $this->userTable->getRow($id);
		
		if (!$row)
			Globals::error('用户ID无效。');
		
		$this->view->row		= $row;
		$this->view->groupData	= $this->groupTable->listAll(null, 'id ASC');
	}
	
	public function modifyPostAction()
	{
		$id = $this->getIntParam('id');
		$result = $this->userTable->modify($this->getParams('username,groupid,realname'), $id);
		$this->log('修改用户资料'.($result ? '成功' : '失败').'(id: '.$id.')');
		$this->redirectToAction();
	}
	
	public function modifyPasswordAction()
	{
		$id	= $this->getIntParam('id');
		$row= $this->userTable->getRow($id);
		
		if (!$row)
			Globals::error('用户ID无效。');
		
		$this->view->row = $row;
	}
	
	public function modifyPasswordPostAction()
	{
		$id = $this->getIntParam('id');
		$result = $this->userTable->modify($this->getParams('password'), $id);
		$this->log('修改用户密码'.($result ? '成功' : '失败').'(id: '.$id.')');
		$this->redirectToAction();
	}
	
	public function deleteAction()
	{
		$id = $this->getIntParam('id');
		$result = $this->userTable->delete($id);
		$this->log('删除用户'.($result ? '成功' : '失败').'(id: '.$id.')');
		$this->redirectToAction();
	}
}
